package com.gallop.mq.core.template;

import com.gallop.mq.core.exception.MQException;
import lombok.Data;
import org.springframework.lang.Nullable;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Data
public class PendingReply {

    private volatile String savedReplyTo;

    private volatile String savedCorrelation;

    private final CompletableFuture<Object> future = new CompletableFuture<>();

    public <P> P get() {
        try {
            return (P) this.future.get();
        } catch (Exception e) {
            throw new MQException("", e);
//                throw RabbitExceptionTranslator.convertRabbitAccessException(e.getCause()); // NOSONAR lost stack trace
        }
    }

    @Nullable
    public <P> P get(long timeout, TimeUnit unit) {
        try {
            return (P) this.future.get(timeout, unit);
        } catch (Exception e) {
            throw new MQException("", e);
//                throw RabbitExceptionTranslator.convertRabbitAccessException(e.getCause()); // NOSONAR lost stack trace
        }
    }

    public void reply(Object reply) {
        this.future.complete(reply);
    }

    public void returned(Exception e) {
        completeExceptionally(e);
    }

    public void completeExceptionally(Throwable t) {
        this.future.completeExceptionally(t);
    }

}
